﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using DevComponents.DotNetBar.Rendering;
using Kxzz.Common;
using Kaixin001.Msg;
using KxzzEntity.FriendsEntity;
using Entity.MsgEntity;
using System.Text.RegularExpressions;

namespace Kxzz
{
    public partial class frmSendMsg : DevComponents.DotNetBar.Office2007Form
    {
        #region 变量
        private IniHelper iniHelper = new IniHelper(Application.StartupPath + "//Config//config.ini");
        private frmMain theParentForm;
        private FriendEntity friend;
        private MessageGroupEntity mge;
        private bool busyActivating;
        private delegate void delegateVoid();
        #endregion

        #region 属性
        private bool hasMessages;
        /// <summary>
        /// 是否存在有消息
        /// </summary>
        public bool HasMessages
        {
            get { return hasMessages; }
            set { hasMessages = value; }
        }

        private string uid;
        /// <summary>
        /// 聊天对象ID
        /// </summary>
        public string Uid
        {
            get { return uid; }
            set { uid = value; }
        }
        #endregion

        #region 构造函数及初始化
        public frmSendMsg(frmMain MainForm)
        {
            InitializeComponent();

            #region 初始化界面
            if (this.iniHelper.read("Setup", "skin") != "")
            {
                eOffice2007ColorScheme colorScheme = (eOffice2007ColorScheme)Enum.Parse(typeof(eOffice2007ColorScheme), this.iniHelper.read("Setup", "skin"));
                this.Office2007ColorTable = colorScheme;
            }
            #endregion

            this.theParentForm = MainForm;
        }

        private void frmSendMsg_Load(object sender, EventArgs e)
        {
            try
            {
                IniFace();

                this.userInfo1.InitValue(this.Name);
                if (this.HasMessages)
                {
                    mge = (MessageGroupEntity)this.Tag;
                    this.mertbSendHistory.Clear();
                    InitMessage(mge);
                }
                else
                {
                    friend = (FriendEntity)this.Tag;
                }
                this.Show();
                this.RTBfocus();
            }
            catch (Exception ex)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show(
                        ex.Message,
                        "错误",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 界面操作
        private void frmSendMsg_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmMain frm = this.theParentForm;
            frm.forms.Romove(this);
        }

        private void butClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void butSend_Click(object sender, EventArgs e)
        {
            delegateVoid dVoid = new delegateVoid(this.EnableWhenSend);

            try
            {
                this.BeginInvoke(dVoid);

                string message = GetSendMsg();
                message = GetSendMessage(message);
                MsgHelper msgHelper = new MsgHelper(Init.Kaixin001Helper);
                bool blnResult = false;
                if (this.HasMessages)
                {
                    blnResult = msgHelper.ReplyMessage(mge.ThreadMid, mge.Uid, message, "html");
                }
                else
                {
                    blnResult = msgHelper.SendMessage(friend.Uid, message, "html");
                }

                if (blnResult)
                {
                    this.mertbSendHistory.AppendText(Init.Kaixin001Helper.User.Name + " " + DateTime.Now.ToString() + "\n" + this.mertbSend.Text + "\n");
                    this.mertbSend.Clear();
                }
                else
                {
                    this.mertbSendHistory.AppendText(DateTime.Now.ToString() + ":" + this.mertbSend.Text + "发送失败！\n");
                }
            }
            catch (Exception ex)
            {
                this.mertbSendHistory.AppendText(DateTime.Now.ToString() + ":" + ex.Message + "\n");
            }
            finally
            {
                this.RTBfocus();
                this.BeginInvoke(dVoid);
            }
        }

        private void frmSendMsg_Activated(object sender, EventArgs e)
        {
            //   这几句话放在开头   
            if (busyActivating)
            {
                return;
            }
            busyActivating = true;

            if (this.HasMessages)
            {
                this.mertbSendHistory.Clear();
                mge = (MessageGroupEntity)this.Tag;
                InitMessage(mge);
            }
            else
            {
                friend = (FriendEntity)this.Tag;
            }
            this.Show();
            this.RTBfocus();
            Application.DoEvents();

            //   这句话放在最后面   
            busyActivating = false;
        }
        #endregion

        #region PrivateMethod
        #region 将对话记录滚动到最后一行
        /// <summary>
        /// 将对话记录滚动到最后一行
        /// </summary>
        private void RTBfocus()
        {
            this.mertbSend.Focus();
            this.mertbSendHistory.Select(this.mertbSendHistory.TextLength, 0);
            this.mertbSend.Focus();
        }
        #endregion

        private string GetSendMsg()//获得要发送的消息类
        {
            string msg = this.mertbSend.Text.TrimEnd();
            string result = msg;
            string msgFace = this.mertbSend.GetImageInfo();
            string[] strFaces = msgFace.Split('|');
            int intLen = 0;
            foreach (string face in strFaces)
            {
                if (!string.IsNullOrEmpty(face))
                {
                    int index = Convert.ToInt32(face.Split(',')[0]);
                    int intImg = Convert.ToInt32(face.Split(',')[1]);
                    string img = "{$" + (intImg + 1).ToString() + "}";
                    if (result.Length >= index + intLen)
                    {
                        result = result.Insert(index + intLen, img);
                        intLen += img.Length;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取发送的信息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public string GetSendMessage(string message)
        {
            string result = message;
            if (!string.IsNullOrEmpty(message))
            {
                Regex regex = new Regex("\\{\\$(?<index>\\d+)\\}");
                MatchCollection matchs = regex.Matches(message);

                if (matchs.Count > 0)
                {
                    foreach (Match match in matchs)
                    {
                        int intImg = Convert.ToInt32(match.Groups["index"].Value);
                        string img = "<img src=\"http://img1.kaixin001.com.cn/i/face/" + intImg.ToString() +
                        ".gif\" title=\"" + Init.FaceContent[intImg] + "\" border=\"0\">";
                        result = Regex.Replace(result, "\\{\\$" + intImg.ToString() + "\\}", img);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取图片信息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public ImgMsgEntity GetImagesMessage(string message)
        {
            ImgMsgEntity imgMsg = new ImgMsgEntity();
            imgMsg.Msg = message;
            int lastLen = 0;

            if (!string.IsNullOrEmpty(message))
            {
                Regex regex = new Regex("\\{\\$(?<index>\\d+)\\}");
                MatchCollection matchs = regex.Matches(message);

                if (matchs.Count > 0)
                {
                    foreach (Match match in matchs)
                    {
                        int intImg = Convert.ToInt32(match.Groups["index"].Value);
                        imgMsg.Img += (match.Index - lastLen).ToString() + "," + intImg.ToString() + "|";
                        imgMsg.Msg = imgMsg.Msg.Replace("{$" + intImg.ToString() + "}", string.Empty);
                        lastLen += intImg.ToString().Length + 3;
                    }
                }
            }
            //if (imgMsg.Img.EndsWith("|"))
            //{
            //    imgMsg.Img = imgMsg.Img.Substring(0, imgMsg.Img.Length - 1);
            //}
            return imgMsg;
        }

        private void InitMessage(MessageGroupEntity mge)
        {
            if (this.HasMessages)
            {
                foreach (MessageEntity me in mge.MessageList)
                {

                    Regex regex = new Regex("\\{\\$(?<index>\\d+)\\}");
                    MatchCollection matchs = regex.Matches(me.Message);
                    if (matchs.Count > 0)
                    {
                        ImgMsgEntity imgMsg = GetImagesMessage(me.Message);
                        this.mertbSendHistory.AppendText(me.SendUser + " " + me.SendTime + "\n");

                        if (!string.IsNullOrEmpty(imgMsg.Img))
                        {
                            string[] imagePos = imgMsg.Img.Split('|');
                            int addPos = 0;//
                            int currPos = 0;//当前正要添加的文本位置
                            int textPos = 0;
                            for (int i = 0; i < imagePos.Length - 1; i++)
                            {
                                string[] imageContent = imagePos[i].Split(',');//获得图片所在的位置、图片名称 
                                currPos = Convert.ToInt32(imageContent[0]);//获得图片所在的位置
                                addPos = currPos - textPos;

                                this.mertbSendHistory.AppendText(imgMsg.Msg.Substring(textPos, addPos));
                                this.mertbSendHistory.SelectionStart = this.mertbSendHistory.TextLength;

                                textPos = currPos;

                                Image image;
                                if (this.mertbSendHistory.findPic(imageContent[1]) == null)
                                {
                                    image = Init.ImageListFace.Images[int.Parse(imageContent[1])-1];
                                }
                                else
                                {
                                    image = this.mertbSendHistory.findPic(imageContent[1]).Image;
                                }

                                //显示图片
                                DevComponents.DotNetBar.ButtonItem item = new DevComponents.DotNetBar.ButtonItem();
                                item.Tag = imageContent[1];
                                item.Tooltip = Init.FaceContent[int.Parse(imageContent[1]) - 1];
                                item.Size = new Size(16, 16);
                                item.Image = image;
                                this.mertbSendHistory.addGifControl(Convert.ToUInt32(item.Tag), item.Image);
                            }
                            this.mertbSendHistory.AppendText(imgMsg.Msg.Substring(textPos, imgMsg.Msg.Length - textPos) + "  \n");
                        }
                    }
                    else
                    {
                        this.mertbSendHistory.AppendText(me.SendUser + " " + me.SendTime + "\n" + me.Message + "\n");
                    }
                }
            }
        }

        private void EnableWhenSend()
        {
            this.scMsg.Panel2.Enabled = !this.scMsg.Panel2.Enabled;
        }

        #region 表情菜单 单击事件
        private void item_Click(object sender, EventArgs e)//表情单击事件代码
        {
            DevComponents.DotNetBar.ButtonItem butItem = sender as DevComponents.DotNetBar.ButtonItem;
            this.mertbSend.addGifControl(
                Convert.ToUInt32(butItem.Tag),
                (System.Drawing.Image)Init.ImageListFace.Images[(int)butItem.Tag]);
        }
        #endregion

        #region 初始化表情菜单
        private void IniFace()
        {
            int j = 0;
            DevComponents.DotNetBar.ItemContainer itemCon = null;
            for (int i = 0; i < 98; i++)
            {
                DevComponents.DotNetBar.ButtonItem item = new DevComponents.DotNetBar.ButtonItem();
                item.Tag = i;
                item.Tooltip = Init.FaceContent[i];
                item.Size = new Size(16, 16);
                item.Image = Init.ImageListFace.Images[i];
                if (i % 20 == 0)
                {
                    DevComponents.DotNetBar.ItemContainer itemC = new DevComponents.DotNetBar.ItemContainer();
                    this.trtFaceSet.SubItems.Add(itemC, j);
                    itemCon = itemC;
                    itemCon.Name = i.ToString();
                    itemCon.MinimumSize = new Size(0, 0);
                    j++;
                }
                itemCon.SubItems.Add(item, i % 20);
                item.Click += new EventHandler(item_Click);
            }
        }
        #endregion
        #endregion
    }
}
